import {
    request2Promise,
    apiGET,
    apiPOST,
    apiUPLOAD
} from "@/common/services/apiRequest.js"
import {
    dateFormat
} from "../../../common/utils/timeUtil.js";

import {
    _mockUnitDetailData
} from "./mockData.js"

/**
 * 获取文章内容
 * @param {String} id 文章id
 */
function getUnitDetailData(id) {
    console.log("getUnitDetailData", id);
    if (!id) {
        throw new Error("getUnitDetailData 参数错误")
    }
    return request2Promise(apiGET, {
        url: `/v1/article/info?id=${id}`
    })
}

/**
 * 文章详情操作类型
 */
const ENUM_OPERATE = {
    READ: {
        icon: "/static/images/unit-detail/read.png",
        name: "导读",
        value: "read",
        progress: 100
    },
    WORD: {
        icon: "/static/images/unit-detail/word.png",
        name: "词汇学习",
        value: "word",
        progress: 100
    },
    TEACH: {
        icon: "/static/images/unit-detail/teach.png",
        name: "原文讲解",
        value: "teach",
        progress: 100
    },
    TEST: {
        icon: "/static/images/unit-detail/test.png",
        name: "阅读理解",
        value: "test",
        progress: 100
    },
    PDF: {
        icon: "/static/images/unit-detail/pdf.png",
        name: "听写",
        value: "pdf",
        progress: 100
    },
    ALOUD: {
        icon: "/static/images/unit-detail/aloud.png",
        name: "全文朗读",
        value: "aloud",
        progress: 100
    }
}

/**
 * 获取阅读引导操作列表
 */
function getEngageOperate() {
    return {
        cnTitle: "阅读引导",
        enTitle: "ENGAGE",
        operateList: [ENUM_OPERATE.READ, ENUM_OPERATE.WORD]
    }
}

/**
 * 获取丰富理解操作列表
 */
function getEnrichOperate() {
    return {
        cnTitle: "丰富理解",
        enTitle: "ENRICH",
        operateList: [ENUM_OPERATE.TEACH, ENUM_OPERATE.TEST, ENUM_OPERATE.PDF, ENUM_OPERATE.ALOUD]
    }
}

/**
 * 跳转文章详情子页面
 * @param {String} operateType 操作类型
 * @param {Object} unit 文章对象
 */
function gotoSubPages(operateType, unit) {
    let url;
    let type;
    switch (operateType) {
        case ENUM_OPERATE.READ.value:
            url = '/pages/unit-detail/subpages/read/read';
            type = ENUM_OPERATE.READ;
            break;
        case ENUM_OPERATE.WORD.value:
            url = '/pages/unit-detail/subpages/word/word';
            type = ENUM_OPERATE.WORD;
            break;
        case ENUM_OPERATE.TEACH.value:
            url = '/pages/unit-detail/subpages/teach/teach';
            type = ENUM_OPERATE.TEACH;
            break;
        case ENUM_OPERATE.TEST.value:
            url = '/pages/unit-detail/subpages/test/test';
            type = ENUM_OPERATE.TEST;
            break;
        case ENUM_OPERATE.PDF.value:
            url = '/pages/unit-detail/subpages/pdf/pdf';
            type = ENUM_OPERATE.PDF;
            break;
        case ENUM_OPERATE.ALOUD.value:
            url = '/pages/unit-detail/subpages/aloud/aloud';
            type = ENUM_OPERATE.ALOUD;
            break;
        default:
            break;
    }
    if (url) {
        uni.navigateTo({
            url,
            success: (res) => {
                res.eventChannel.emit("openPage", {
                    unit,
                    type
                })
            }
        })
    }
}

/**
 * 获取听写PDF
 * @param {Object} id
 */
function getPdfPath(id) {
    console.log("getPdfPath", id);
    if (!id) {
        throw new Error("getPdfPath 参数错误")
    }
    return request2Promise(apiGET, {
        url: `/system/article/dowOriginalExplanationSpace?id=${id}`
    })
}

/**
 * 下载pdf
 * @param {Object} fileUrl pdf下载地址
 */
function downloadPDF(fileUrl) {
    uni.downloadFile({
        url: fileUrl,
        success: (res) => {
            if (res.statusCode == 200) {
                // 下载成功
                const filePath = res.tempFilePath; // 下载文件的临时路径
                // #ifndef APP-PLUS
                const fileManager = uni.getFileSystemManager();
                // #ifdef MP-WEIXIN
                fileManager.saveFile({
                    tempFilePath: filePath,
                    success: (saveRes) => {
                        // 保存成功，打开文件
                        uni.openDocument({
                            filePath: saveRes.savedFilePath,
                            success: (file) => {
                                console.log("file-open-success", file)
                            }
                        })
                    }
                })
                // #endif
                // #endif
                // #ifdef APP-PLUS
                uni.saveFile({
                    tempFilePath: filePath,
                    success: (listRes) => {
                        // 为了拿到文件保存的详细路径
                        plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
                            // 拿到 _doc 所在的完整路径
                            console.log("pdf download path", fs.root.fullPath);
                            // 弹出文件保存路径
                            uni.showModal({
                                title: "下载保存成功",
                                content: `已存至：${fs.root.fullPath}${listRes.savedFilePath}`,
                                showCancel: false
                            })
                        }, function(e) {
                            console.log("request file system failed:", e.message)
                        })
                        // 保存成功，打开文件
                        uni.openDocument({
                            filePath,
                            success: (file) => {
                                console.log("file-open-success", file)
                            }
                        })
                    },
                    fail: () => {
                        uni.showToast({
                            title: "保存文件失败",
                            icon: 'none'
                        })
                    }
                })
                // #endif
            } else {
                uni.showToast({
                    title: "下载失败",
                    icon: 'none'
                })
            }
        },
        fail: () => {
            uni.showToast({
                title: "下载请求失败",
                icon: "none"
            })
        }
    })
}

/**
 * 上传文件
 */
function uploadFile(filePath) {
    console.log("uploadFile", filePath);
    if (!filePath) {
        throw new Error("uploadFile 参数错误")
    }
    return request2Promise(apiUPLOAD, {
        url: `/file/upload`,
        filePath,
        name: "multipartFile"
        // name: "file"
    })
}

/**
 * 下载单词语音
 * @param {Object} word
 */
const _wordVoiceResult = {};

function getWordPlayVoicePath(word) {
    return new Promise((resolve, reject) => {
        let filePath = _wordVoiceResult[word];
        if (filePath) {
            resolve(filePath)
        } else {
            uni.downloadFile({
                url: `https://dict.youdao.com/dictvoice?audio=${word}&type=2`,
                success: (res) => {
                    _wordVoiceResult[word] = res.tempFilePath;
                    resolve(res.tempFilePath)
                },
                fail: (err) => {
                    reject()
                }
            })
        }
    })
}

/**
 * 题目类型
 */
const QUESTION_TYPE = {
    WORD: {
        value: 1,
        name: "单词题"
    },
    SINGLE_CHOOSE: {
        value: 2,
        name: "单选题"
    },
    CLOZE: {
        value: 3,
        name: "完型填空题"
    },
    LINE_LINK: {
        value: 4,
        name: "连线题"
    },
    ALOUD: {
        value: 5,
        name: "全文朗读"
    }
}

/** ====================== Question List ==================== */

/**
 * 获取题目列表
 * @param {Object} articleId 章节id
 * @param {Object} questionTypeId 题型
 * @param {Object} num 第几题
 */
function getQuestionList(articleId, questionTypeId, num) {
    let url = "/system/articleExercises/list";
    let data = {
        articleId
    };
    if (questionTypeId) {
        data.questionTypeId = questionTypeId
    }
    if (typeof num == 'number') {
        data.num = num;
    }
    return request2Promise(apiPOST, {
        url,
        data
    })
}

/**
 * 获取重点词汇
 * @param {String} id 文章id
 */
function getUnitWordData(id) {
    console.log("getUnitWordData", id);
    if (!id) {
        throw new Error("getUnitWordData 参数错误")
    }
    return getQuestionList(id, QUESTION_TYPE.WORD.value)
}

/**
 * 获取阅读理解题库
 * @param {Object} id
 */
function getTestData(id) {
    console.log("getTestData", id);
    if (!id) {
        throw new Error("getUnitWordData 参数错误")
    }
    return getQuestionList(id);
}

/**
 * 获取单个类型阅读题库
 * @param {Object} id
 * @param {Object} questionType
 */
function getSingleTypeTestData(id, questionType) {
    return getQuestionList(id, questionType);
}

/**
 * 获取单个阅读题
 * @param {Object} id
 * @param {Object} questionType
 * @param {Object} num
 */
function getSingleTestData(id, questionType, num) {
    return getQuestionList(id, questionType, num);
}

/**
 * 拼接问题列表
 * @param {Object} questionListData
 */
function contatTestQuestionData(questionListData) {
    let result = [];
    Object.keys(questionListData).forEach(key => {
        questionListData[key].forEach(item => {
            result.push(item)
        })
    })
    return result;
}

/** ====================== Answer Submit ==================== */

/**
 * 测评提交
 */
function submitAnswer(articleId, questionTypeId, answer, id, file, number) {
    let url = "/system/articleExercises/answerSubmission";
    let data = {
        articleId,
        questionTypeId,
        answer
    }
    if (id) {
        data.id = id;
    }
    if (file) {
        data.file = file
    }
    if (number != undefined) {
        data.number = number
    }
    return request2Promise(apiPOST, {
        url,
        data
    });
}

/**
 * 单词测评提交
 * @param {Object} articleId
 * @param {Object} answer
 * @param {Object} file
 * @param {Object} number
 */
function submitWordAnswer(articleId, answer, id, file, number) {
    return submitAnswer(articleId, QUESTION_TYPE.WORD.value, answer, id, file, number);
}

/**
 * 单选测评提交
 * @param {Object} articleId
 * @param {Object} id
 * @param {Object} answer
 */
function submitSingleChooseAnswer(articleId, answer, id) {
    return submitAnswer(articleId, QUESTION_TYPE.SINGLE_CHOOSE.value, answer, id)
}

/**
 * 完形填空测评提交
 * @param {Object} articleId
 * @param {Object} id
 * @param {Object} answer
 */
function submitClozeAnswer(articleId, answer, id) {
    return submitAnswer(articleId, QUESTION_TYPE.CLOZE.value, answer, id);
}

/**
 * 连线题提交
 * @param {Object} articleId
 * @param {Object} id
 * @param {Object} answer
 */
function submitLineLinkAnswer(articleId, answer, id) {
    return submitAnswer(articleId, QUESTION_TYPE.LINE_LINK.value, answer, id);
}

/**
 * 全文朗读提交
 * @param {Object} articleId
 * @param {Object} answer
 * @param {Object} file
 * @param {Object} number
 */
function submitAloudAnswer(articleId, answer, file, number) {
    return submitAnswer(articleId, QUESTION_TYPE.ALOUD.value, answer, null, file, number)
}

/** ====================== Answer Result ==================== */

/**
 * 获取测评结果
 * @param {Object} id
 * @param {Object} questionType
 */
function getAnswerResult(id, questionType) {
    let url = "/system/articleExercises/getAnswerSubmissionResult";
    let data = {
        articleId: id,
        questionTypeId: questionType
    }
    return request2Promise(apiPOST, {
        url,
        data
    });
}

/**
 * 获取单词测评结果
 * @param {Object} articleId
 */
function getUnitWordAnswerResult(articleId) {
    return getAnswerResult(articleId, QUESTION_TYPE.WORD.value)
}

/**
 * 获取单选题测评结果
 * @param {Object} id
 */
function getSingleChooseAnswerResult(articleId) {
    return getAnswerResult(articleId, QUESTION_TYPE.SINGLE_CHOOSE.value);
}

/**
 * 获取完形填空评测结果
 * @param {Object} articleId
 */
function getClozeAnswerResult(articleId) {
    return getAnswerResult(articleId, QUESTION_TYPE.CLOZE.value)
}

/**
 * 获取连线题评测结果
 * @param {Object} articleId
 */
function getLineLinkAnswerResult(articleId) {

    return getAnswerResult(articleId, QUESTION_TYPE.LINE_LINK.value)
}

/**
 * 获取全文朗读评测结果
 * @param {Object} articleId
 */
function getAloudAnswerResult(articleId) {

    return getAnswerResult(articleId, QUESTION_TYPE.ALOUD.value)
}

/**
 * 阅读理解评测结果
 * @param {Object} articleId
 */
function getTestAnswerResult(articleId) {
    return Promise.all([
        getSingleChooseAnswerResult(articleId),
        getClozeAnswerResult(articleId),
        getLineLinkAnswerResult(articleId)
    ]);
}

/**
 * 阅读理解结果拼接
 * @param {Object} results
 */
function contatTestAnswerResult(results) {
    if (!results) return null;
    let total = 0;
    let already = 0;
    let score = 0;
    let list = [];
    results.forEach(item => {
        total = total + item.total;
        already = already + item.list.length;
        // score = score + item.comprehensiveScore; 
        // 阅读理解得分应该按 题目正确数量来计算
        let correctCount = 0;
        item.list.forEach(tempItem => {
            list.push(tempItem);
            if (tempItem.isCorrect) {
                correctCount = correctCount + 1;
            }
        })
        score = parseFloat(correctCount / total).toFixed(2);
    })
    return {
        total,
        already,
        comprehensiveScore: score,
        list
    }
}

/**
 * 重置答题结果
 * @param {Object} articleId
 * @param {Object} questionTypeId
 */
function restartAnswer(articleId, questionTypeId) {

    return request2Promise(apiPOST, {
        url: `/system/articleExercises/restartSubmission`,
        data: {
            articleId,
            questionTypeId
        }
    })
}

module.exports = {
    getUnitDetailData,

    ENUM_OPERATE,
    getEngageOperate,
    getEnrichOperate,

    gotoSubPages,

    getPdfPath,
    downloadPDF,

    uploadFile,

    getWordPlayVoicePath,

    QUESTION_TYPE,

    getQuestionList,
    getUnitWordData,
    getTestData,
    getSingleTypeTestData,
    getSingleTestData,
    contatTestQuestionData,

    submitAnswer,
    submitWordAnswer,
    submitSingleChooseAnswer,
    submitClozeAnswer,
    submitLineLinkAnswer,
    submitAloudAnswer,

    getAnswerResult,
    getUnitWordAnswerResult,
    getSingleChooseAnswerResult,
    getClozeAnswerResult,
    getLineLinkAnswerResult,
    getAloudAnswerResult,
    getTestAnswerResult,
    contatTestAnswerResult,

    restartAnswer
}